import React,{Component,Fragment} from 'react';
import {Layout,Form,Icon,Input,Button,Checkbox,Cascader,Select,Row,Col,AutoComplete,message} from 'antd';
import styled from 'styled-components';
import { connect } from 'dva';
const {Footer,Content}=Layout;
const Option=Select.Option;
const AutoCompleteOption = AutoComplete.Option;
const FormItem=Form.Item;
class Login extends Component{
    handleSubmit=event => {
        event.preventDefault();
        this.userForm.props.form.validateFields((err,values) => {
                if (err) {
                    message.error('输入不合法!');
                } else {
                    this.props.dispatch({
                        type: this.props.isLogin?'login/login':'login/signup',
                        payload:values
                    });
                }
        });
    }
    
    changeLoginStatus=() => {
        this.props.dispatch({
            type:'login/changeLoginStatus'
        });
    }
    render() {
        return (
            <Layout>
                <Content>
                    <LoginForm
                        isLogin={this.props.isLogin}
                        handleSubmit={this.handleSubmit}
                        wrappedComponentRef={inst => this.userForm=inst}
                        changeLoginStatus={this.changeLoginStatus}
                        errorInfo={this.props.errorInfo}
                    />
                </Content>
                <Footer style={{ textAlign: 'center' }}> 管理系统 ©2019</Footer>
            </Layout>
       )
   }
}

export default connect(
    state => ({
        ...state.login,
        loading:state.loading.models.login
    })
)(Login);

class LoginForm extends Component{
    state={autoCompleteResult:[],confirmDirty:false}
    handleWebsiteChange=(value) => {
        //声明变量
        let autoCompleteResult;
        //判断数据存在否，存在，进行映射，不存在赋值为空
        if (value) {
            //数组映射，先遍历 再改变数据
            autoCompleteResult=['.com','.cn','.org'].map(domain=>`${value}${domain}`);
        } else {
            autoCompleteResult=[];
        }
        this.setState({autoCompleteResult});
    }
    handleConfirmBlur = (e) => {
        const value = e.target.value;
        this.setState({ confirmDirty: this.state.confirmDirty || !!value });
      }
     //自定义校验 
    compareToFirstPassword=(rule,value,callback) => {
        const form=this.props.form;
        if (value && value !== form.getFieldValue('password')) {
            callback('密码不匹配');
        } else {
            callback();
        }
    }
    //自定义校验 
    validateToNextPassword=(rule,value,callback) => {
        const form=this.props.form;
        if (value&&this.state.confirmDirty) {
            form.validateFields(['confirm'],{force:true});
        }
        callback();
    }
    render() {
        const {form: {getFieldDecorator},isLogin,handleSubmit}=this.props;
        const formItemLayout={
            labelCol:{
                span:4
            },
            wrapperCol: {
                span:20
            }

        }
        const tailFormItemLayout={
            wrapperCol: {
                span: 20,
                offset:4
            }
        }
        //级联
        const addresses=[
            {
                value:'guangdong',
                label: '广东',
                children: [
                    {
                        value:'guangzhou',
                        label: '广州',
                    },
                    {
                        value:'shenzhen',
                        label: '深圳',
                    }
                ]
            },
            {
                value:'shandong',
                label: '山东',
                children: [
                    {
                        value:'jinan',
                        label: '济南',
                    },
                    {
                        value:'shouguang',
                        label: '寿光',
                    }
                ]
            }
        ]
        //手机前缀
        const countrySelector=getFieldDecorator('prefix',{initialValue: '86'})(
            <Select style={{width: 70}}>
                <Option value="86">+86</Option>
                <Option value="87">+87</Option>
            </Select>
        );
        //遍历 先自动完成后显示 赋值
        const websiteOptions=this.state.autoCompleteResult.map(website => (
            <AutoCompleteOption key={website}>{website}</AutoCompleteOption>
        ));
        return (
            <FormWrapper>
              <Form onSubmit={handleSubmit} style={{width:isLogin?'300px':'500px'}}>
                <h3>欢迎注册</h3>
                <FormItem label="用户名" {...formItemLayout}>
                            {
                                getFieldDecorator('username',{
                                    //规则
                                    rules:[{required:true,message:'请输入你的用户名'}]
                                })(<Input prefix={<Icon type="user" style={{color:'rbga(0,0,0,.25)'}}/>} placeholder="用户名"/>)
                            }
                </FormItem>
                <FormItem label="密码" {...formItemLayout}>
                            {
                                getFieldDecorator('password',{
                            rules: [{required: true,message: '请输入你的密码'},
                                {validator:this.validateToNextPassword}
                                ]
                                //prefix  前缀
                                })(<Input prefix={<Icon type="lock" style={{color:'rbga(0,0,0,.25)'}}/>} placeholder="密码"/>)
                            }
                    </FormItem>
                {
                        !isLogin&&(
                            <FormItem label="确认密码" {...formItemLayout}>
                            {
                                getFieldDecorator('confirm',{
                            rules: [{required: true,message: '请输入你的确认密码'},
                                {validator:this.compareToFirstPassword}
                                ]
                                })(<Input prefix={<Icon type="lock" style={{color:'rbga(0,0,0,.25)'}}/>} placeholder="确认密码"/>)
                            }
                          </FormItem>
                        )
                }
                {
                        !isLogin&&(
                            <FormItem label="邮箱" {...formItemLayout}>
                            {
                                getFieldDecorator('email',{
                            rules: [{type:'email',message:'必须输入合法的邮箱地址'},{required:true,message:'请输入邮箱'}]
                                })(<Input prefix={<Icon type="mail" style={{color:'rbga(0,0,0,.25)'}}/>} placeholder="密码"/>)
                            }
                           </FormItem>
                        )
                    }
                {
                        !isLogin&&(
                            <FormItem label="住址" {...formItemLayout}>
                            {
                               getFieldDecorator('address',{
                                 initialValue:["guangdong","guangzhou"],
                                 rules: [{type:'array',required:true,message:'必须输入合法的地址'}]
                                })(<Cascader options={addresses}/>)
                            }
                          </FormItem>
                        )
                }
                {
                        !isLogin&&(
                            <FormItem label="手机号" {...formItemLayout}>
                            {
                               getFieldDecorator('phone',{
                                 rules: [{required:true,message:'必须输入合法的手机号'}]
                               })(<Input addonBefore={countrySelector} style={{width:'100%'}}/>)
                            }
                           </FormItem>
                        )
                }
                {
                        !isLogin&&(
                            <FormItem label="个人主页" {...formItemLayout}>
                            {
                               getFieldDecorator('website',{
                                 rules: [{required:true,message:'必须输入合法的网址'}]
                            })(
                                <AutoComplete
                                dataSource={websiteOptions}
                                onChange={this.handleWebsiteChange}
                                placeholder="网址"
                                >
                                    <Input/>
                                </AutoComplete>
                            )
                                }
                            </FormItem>
                        )
                }
                {
                        !isLogin&&(
                            <FormItem label="验证码" {...formItemLayout} extra="证明你不是机器人">
                              <Row gutter={8}>
                                <Col span={12}>
                                {
                                       getFieldDecorator('captcha',{
                                         rules: [{required:true,message:'必须输入验证码'}]
                                   })(<Input />)
                                }
                                </Col>
                                <Col span={12}>
                                    <Button>获取验证码</Button>
                                </Col>
                              </Row>
                           </FormItem>
                        )
                    }
                {
                        !isLogin&&(
                            <FormItem {...tailFormItemLayout}>
                                {getFieldDecorator('agreement', {
                                    valuePropName: 'checked',
                                })(
                                    <Checkbox>我已经阅读并同意 <a href="">协议</a></Checkbox>
                                )}
                            </FormItem>
                        )
                }
                {
                        isLogin?(<FormItem>
                                    <Button type="primary" htmlType="submit" style={{width:'100%'}}>登录</Button>
                                        没有账号? <a href="#" onClick={this.props.changeLoginStatus}>立刻注册!</a>
                                    </FormItem>):(
                                <FormItem>
                               <Button type="primary" htmlType="submit" style={{width:'100%'}}>注册</Button>
                            已有账号? <a href="#" onClick={this.props.changeLoginStatus}>立即登录!</a>
                                </FormItem>
                        )
                }
                </Form>
            </FormWrapper>

        )
  }
}

// Form.create(options)#
//使用方式如下：
//class CustomizedForm extends React.Component {}
//CustomizedForm = Form.create({})(CustomizedForm);
LoginForm = Form.create()(LoginForm);
const FormWrapper=styled.div`
   display:flex;
   justify-content:center;
   align-items:center;
   height:100%;
   h3 {
    text-align:center;
   }
   form {
       border:1px solid #999;
       border-radius:5px;
       padding:20px;
   }
   `